package com.aloda.interceptor;

import com.aloda.context.UserBaseContext;
import com.aloda.dto.user.UserSafetyDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户登录校验拦截器
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否需要拦截
        UserSafetyDTO user = UserBaseContext.getUser();
        if (user == null){
            response.setStatus(401);
            return false;
        }
        //2.有用户放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserBaseContext.removeUser();
    }
}
